package com.mrd.gtimpframe.action;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.gtimpframe.entity.AgentRef;
import com.mrd.gtimpframe.entity.Attachment;
import com.mrd.gtimpframe.entity.CompanyInfo;
import com.mrd.gtimpframe.service.AgentRefService;
import com.mrd.gtimpframe.service.AttachmentService;
import com.mrd.gtimpframe.service.ComAuditService;
import com.mrd.gtimpframe.service.CompanyInfoService;
import com.mrd.util.JsonBinder;
import com.mrd.util.LoginUtil;
import com.mrd.util.ResponseUtils;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Resource
    private CompanyInfoService companyInfoService;
    @Resource
    private AgentRefService agentRefService;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private ComAuditService comAuditService;

    /**
     * 隐性客户注册页面
     */
    @RequestMapping("/tacitCustomerRegistration")
    public String tacitCustomerRegistration(String comInfoId, Model model) {
        if (StringUtils.isNotEmpty(comInfoId)) {
            model.addAttribute("companyInfo", companyInfoService.selectWithAduit(comInfoId));
        }
        return "gtimpframe/orderFor/tacitCustomerRegistration";
    }

    /**
     * 获取已上传的附件
     */
    @RequestMapping("/getAttachment")
    public void getAttachment(String comInfoId, HttpServletResponse response) {
        String agentId = LoginUtil.getLoginUser().getCompany().getId();
        AgentRef agentRef = agentRefService.getAgentRef(agentId, comInfoId);
        getAttachmentByAgentRefIdAndPrint(response, agentRef.getAgentRefId());
    }

    /**
     * 获取已上传的附件
     */
    @RequestMapping("/getAttachmentForAudit")
    public void getAttachmentForAudit(String auditId, HttpServletResponse response) {
        String agentRefId = comAuditService.getAgentRefIdByAuditId(auditId);
        getAttachmentByAgentRefIdAndPrint(response, agentRefId);
    }

    /**
     * 根据委托关系ID获取附件并输出
     *
     * @param response   httpResponse
     * @param agentRefId 委托关系ID
     */
    private void getAttachmentByAgentRefIdAndPrint(HttpServletResponse response, String agentRefId) {
        PageHelper.startPage(1, 15);
        List<Attachment> attachments = attachmentService.getAttachmentList(agentRefId);
        PageInfo<Attachment> pi = new PageInfo<>(attachments);
        Page<Map<String, Object>> pMap = new PageImpl(attachments, new Jqgrid().getPage(), pi.getTotal());
        JsonBinder jsonBinder = JsonBinder.buildNormalBinder();
        jsonBinder.setDateFormat("yyyy-MM-dd HH:mm:ss");
        ResponseUtils.renderJson(response, jsonBinder.toJson(pMap));
    }

    /**
     * 保存公司(被代理)信息
     */
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(CompanyInfo companyInfo) {
        if (StringUtils.isEmpty(companyInfo.getName())) {
            return Result.newFailInstance("请输入公司名称");
        }
        if (StringUtils.isEmpty(companyInfo.getUniteCode())) {
            return Result.newFailInstance("请输入统一社会信用代码");
        } else if (companyInfo.getUniteCode().length() != 18) {
            return Result.newFailInstance("统一社会信用代码必须为18位");
        }
        try {
            return companyInfoService.saveOrUpdate(companyInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.newFailInstance(e.getMessage());
        }
    }

    /**
     * 提交注册信息
     */
    @RequestMapping("/recessiveComSubmit")
    @ResponseBody
    public Result recessiveComSubmit(String comInfoId) {
        if (comInfoId == null) {
            return Result.newFailInstance("操作失败");
        }
        return companyInfoService.recessiveComSubmit(comInfoId);
    }

    /**
     * 隐性公司附件上传
     */
    @RequestMapping("/uploadCompanyAttachment")
    @ResponseBody
    public Result uploadCompanyAttachment(MultipartFile file, String comInfoId) {
        if (StringUtils.isEmpty(comInfoId)) {
            return Result.newFailInstance("操作失败，请刷新页面再试");
        }
        try {
            return companyInfoService.uploadCompanyAttachment(file, comInfoId);
        } catch (Exception e) {
            return Result.newFailInstance("操作失败，请稍后再试");
        }
    }

    /**
     * 删除附件
     *
     * @param id 附件id
     */
    @RequestMapping("/attachmentDel")
    @ResponseBody
    public Result attachmentDel(String id) {
        if (StringUtils.isEmpty(id)) {
            return Result.newFailInstance("操作失败，请刷新页面再试");
        }
        try {
            attachmentService.deleteattAchment(id);
            return Result.newSuccessInstance("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.newFailInstance("操作失败，请稍后再试");
        }
    }

    /**
     * 下载附件
     */
    @RequestMapping("/downloadComAttachment")
    @ResponseBody
    public void downloadAttachment(HttpServletRequest request, HttpServletResponse response, String id) {
        attachmentService.downloadAttachment(request, response, id);
    }

    /**
     * 获取关系信息
     */
    @RequestMapping("/getAgentRef")
    @ResponseBody
    public AgentRef getAgentRef(String comInfoId) {
        String agentId = LoginUtil.getLoginUser().getCompany().getId();
        return agentRefService.getAgentRef(agentId, comInfoId);
    }

    /**
     * 根据统一社会信用代码获取公司信息
     */
    @RequestMapping("/getCompInfo")
    @ResponseBody
    public CompanyInfo getCompanyInfo(String uniteCode) {
        return companyInfoService.selectByUnitCode(uniteCode);
    }
}
